package com.cauli.manage.user.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.cauli.manage.user.model.vo.UserDetailVO;
import com.cauli.manage.user.model.dto.UserUpdateDTO;
import com.cauli.manage.user.model.entity.User;
import com.cauli.manage.user.service.UserService;
import com.cauli.utils.exception.MyException;
import com.cauli.utils.util.FileUploadUtils;
import com.cauli.utils.util.ResultResponse;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.qiwenshare.common.anno.MyLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author Cauli
 * @date 2023/2/24 10:26
 * @description 个人信息 前端控制器
 */
@Api(tags = "个人信息")
@ApiSort(8)
@RestController
@RequestMapping("/user/profile")
public class ProfileController {
    @Autowired
    private UserService userService;

    public static final String CURRENT_MODULE = "个人信息";

    @ApiOperationSupport(order = 1)
    @ApiOperation("获取个人信息")
    @GetMapping
    public ResultResponse<UserDetailVO> getProfile() {
        long loggedInUserId = StpUtil.getLoginIdAsLong();
        UserDetailVO userDetailVO = userService.getUserDetail(loggedInUserId);
        return ResultResponse.success().data(userDetailVO);
    }

    @MyLog(operation = "修改个人信息", module = CURRENT_MODULE)
    @ApiOperationSupport(order = 2)
    @ApiOperation("修改个人信息")
    @PutMapping
    public ResultResponse<Void> updateProfile(@Valid @RequestBody UserUpdateDTO userUpdateDTO) {
        userService.updateUser(userUpdateDTO);
        return ResultResponse.success().message("修改成功");
    }

    @MyLog(operation = "上传用户头像", module = CURRENT_MODULE)
    @ApiOperationSupport(order = 4)
    @ApiOperation("上传用户头像")
    @PostMapping("/uploadAvatar")
    public ResultResponse<String> uploadAvatar(@RequestPart("avatarFile") MultipartFile avatarFile) {
        if (avatarFile.isEmpty()) {
            throw new MyException("用户上传头像失败");
        }
        String avatarUrl = FileUploadUtils.upload("avatar", avatarFile);

        // 根据用户ID查询用户信息
        long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);
        // 更新头像
        user.setAvatar(avatarUrl);
        UserUpdateDTO userUpdateDTO = new UserUpdateDTO();
        BeanUtils.copyProperties(user, userUpdateDTO);
        userService.updateUser(userUpdateDTO);

        return ResultResponse.success().message("修改头像成功").data(avatarUrl);
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("获得下载文件下载链接")
    @GetMapping("/getFileUrl/{fileName}")
    public void download(HttpServletResponse httpServletResponse, @PathVariable String fileName) {
        String date = fileName.substring(0, fileName.indexOf('_'));
        String classpath = Objects.requireNonNull(getClass().getResource("/")).getPath();
        String md5AndFileName;
        String suffix = "";
        if (fileName.contains(".")) {
            suffix = fileName.substring(fileName.lastIndexOf('.'));
            md5AndFileName = fileName.substring(fileName.indexOf('_') + 1, fileName.lastIndexOf('.'));
        } else {
            md5AndFileName = fileName.substring(fileName.indexOf('_') + 1);
        }
        String completeFileName =  "static/upload/" + date + "/avatar/" + md5AndFileName + suffix;

        File file = new File(classpath + completeFileName);
        try (
                // 读取文件的字节流
                FileInputStream fileInputStream = new FileInputStream(file);
                // 将文件写入输入流
                InputStream inputStream = new BufferedInputStream(fileInputStream);
                // 设置输出流的格式
                ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        ) {
            httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(md5AndFileName + suffix, "UTF-8"));
            httpServletResponse.setContentType("application/octet-stream");

            int bytesRead = 0;
            byte[] buffer = new byte[1024];

            //设置输出流的格式
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
